package com.kevin.springcloud.hystrixzuulserver;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class AccessTokenFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext preCtx = RequestContext.getCurrentContext();
        preCtx.getResponse().setContentType("application/json;charset=utf-8");
        HttpServletRequest req = preCtx.getRequest();

        System.out.println("Zuul Filter:"+ req.getRequestURI());

        Object objAccessToken = req.getHeader("accesstoken");
        if(objAccessToken== null){
            preCtx.setSendZuulResponse(false);
            preCtx.setResponseStatusCode(401);
            preCtx.setResponseBody("{rcode:1,rstr:\"没有token\"}");
            return  null;
        }
        else {
            System.out.println(objAccessToken.toString());
        }
        return null;
    }
}
